/**
 * 测试优化后的娱乐城定时任务逻辑
 * 验证：1.关闭 -> 2.开奖 -> 3.结算 -> 4.创建新期数的执行顺序
 */

const WebSocket = require('ws');
const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
  host: '43.143.253.188',
  port: 3306,
  user: 'root',
  password: 'jack666',
  database: 'test2_nextjs'
};

class CasinoSchedulerTester {
  constructor() {
    this.ws = null;
    this.userId = 2001;
    this.characterId = 2001;
    this.connection = null;
  }

  async connect() {
    try {
      // 连接数据库
      this.connection = await mysql.createConnection(dbConfig);
      console.log('✅ 数据库连接成功');

      // 连接WebSocket
      this.ws = new WebSocket('ws://localhost:3001/user-service/websocket', {
        headers: {
          'Authorization': 'Bearer test-token-2001'
        }
      });

      this.ws.on('open', () => {
        console.log('✅ WebSocket连接成功');
        this.login();
      });

      this.ws.on('message', (data) => {
        try {
          const message = JSON.parse(data.toString());
          this.handleMessage(message);
        } catch (error) {
          console.error('解析消息失败:', error);
        }
      });

      this.ws.on('error', (error) => {
        console.error('WebSocket错误:', error);
      });

    } catch (error) {
      console.error('连接失败:', error);
    }
  }

  login() {
    console.log('🔄 开始登录...');
    this.ws.send(JSON.stringify({ c: 1, d: { username: 'testuser', password: 'testpass' } }));
  }

  handleMessage(message) {
    console.log('📨 收到消息:', JSON.stringify(message, null, 2));

    if (message.act_id === 1 && message.code === 0) {
      console.log('✅ 登录成功');
      this.selectCharacter();
    } else if (message.act_id === 4 && message.code === 0) {
      console.log('✅ 角色选择成功');
      this.startTesting();
    }
  }

  selectCharacter() {
    console.log('🔄 选择角色...');
    this.ws.send(JSON.stringify({ c: 4, d: { characterId: this.characterId } }));
  }

  async startTesting() {
    console.log('\n🎰 开始测试娱乐城定时任务优化逻辑...\n');

    // 1. 检查当前期数状态
    await this.checkCurrentRounds();

    // 2. 等待一段时间观察定时任务执行
    console.log('⏰ 等待30秒观察定时任务执行...');
    setTimeout(() => {
      this.checkCurrentRounds();
    }, 30000);

    // 3. 等待更长时间观察完整流程
    setTimeout(() => {
      this.checkCurrentRounds();
      this.analyzeResults();
    }, 60000);
  }

  async checkCurrentRounds() {
    try {
      console.log('\n📊 检查当前期数状态...');

      // 检查大小玩法当前期数
      const [diceRows] = await this.connection.execute(`
        SELECT id, status, start_time, end_time, num1, num2, num3, sum, is_big, is_odd, is_triple, created_at, updated_at
        FROM casino_dice_rounds 
        WHERE status IN (1, 2) 
        ORDER BY created_at DESC 
        LIMIT 3
      `);

      console.log('🎲 大小玩法期数状态:');
      diceRows.forEach((round, index) => {
        const statusText = round.status === 1 ? '下注中' : round.status === 2 ? '开奖中' : '已结算';
        const timeLeft = round.end_time ? Math.max(0, Math.floor((new Date(round.end_time) - new Date()) / 1000)) : 0;
        console.log(`  ${index + 1}. 期数${round.id}: ${statusText}, 剩余${timeLeft}秒`);
        if (round.num1 && round.num2 && round.num3) {
          console.log(`     开奖结果: ${round.num1},${round.num2},${round.num3} (${round.sum}点${round.is_big ? '大' : '小'}${round.is_odd ? '单' : '双'}${round.is_triple ? '豹子' : ''})`);
        }
      });

      // 检查赤壁玩法当前期数
      const [chibiRows] = await this.connection.execute(`
        SELECT id, status, start_time, end_time, winning_side, battle_report, created_at, updated_at
        FROM casino_chibi_rounds 
        WHERE status IN (1, 2) 
        ORDER BY created_at DESC 
        LIMIT 3
      `);

      console.log('⚔️ 赤壁玩法期数状态:');
      chibiRows.forEach((round, index) => {
        const statusText = round.status === 1 ? '下注中' : round.status === 2 ? '开奖中' : '已结算';
        const timeLeft = round.end_time ? Math.max(0, Math.floor((new Date(round.end_time) - new Date()) / 1000)) : 0;
        const sideNames = { 1: '魏国', 2: '蜀国', 3: '吴国' };
        console.log(`  ${index + 1}. 期数${round.id}: ${statusText}, 剩余${timeLeft}秒`);
        if (round.winning_side) {
          console.log(`     开奖结果: ${sideNames[round.winning_side]}获胜 - ${round.battle_report}`);
        }
      });

    } catch (error) {
      console.error('❌ 检查期数状态失败:', error);
    }
  }

  async analyzeResults() {
    try {
      console.log('\n📈 分析定时任务执行结果...');

      // 分析最近10分钟的期数变化
      const [diceHistory] = await this.connection.execute(`
        SELECT id, status, start_time, end_time, num1, num2, num3, sum, created_at, updated_at
        FROM casino_dice_rounds 
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)
        ORDER BY created_at DESC
      `);

      const [chibiHistory] = await this.connection.execute(`
        SELECT id, status, start_time, end_time, winning_side, battle_report, created_at, updated_at
        FROM casino_chibi_rounds 
        WHERE created_at >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)
        ORDER BY created_at DESC
      `);

      console.log('\n🎲 大小玩法最近期数变化:');
      diceHistory.forEach((round, index) => {
        const statusText = round.status === 1 ? '下注中' : round.status === 2 ? '开奖中' : '已结算';
        const createdTime = new Date(round.created_at).toLocaleTimeString();
        const updatedTime = new Date(round.updated_at).toLocaleTimeString();
        console.log(`  ${index + 1}. 期数${round.id}: ${statusText} (创建:${createdTime}, 更新:${updatedTime})`);
      });

      console.log('\n⚔️ 赤壁玩法最近期数变化:');
      chibiHistory.forEach((round, index) => {
        const statusText = round.status === 1 ? '下注中' : round.status === 2 ? '开奖中' : '已结算';
        const createdTime = new Date(round.created_at).toLocaleTimeString();
        const updatedTime = new Date(round.updated_at).toLocaleTimeString();
        console.log(`  ${index + 1}. 期数${round.id}: ${statusText} (创建:${createdTime}, 更新:${updatedTime})`);
      });

      // 验证执行顺序
      this.validateExecutionOrder(diceHistory, chibiHistory);

    } catch (error) {
      console.error('❌ 分析结果失败:', error);
    }
  }

  validateExecutionOrder(diceHistory, chibiHistory) {
    console.log('\n✅ 验证定时任务执行顺序...');

    // 检查大小玩法执行顺序
    let diceOrderValid = true;
    for (let i = 0; i < diceHistory.length - 1; i++) {
      const current = diceHistory[i];
      const next = diceHistory[i + 1];
      
      // 检查是否有正确的状态转换：下注中 -> 开奖中 -> 已结算
      if (current.status === 1 && next.status === 2) {
        console.log(`  ✅ 大小期数${current.id}: 下注中 -> 开奖中 (正确)`);
      } else if (current.status === 2 && next.status === 3) {
        console.log(`  ✅ 大小期数${current.id}: 开奖中 -> 已结算 (正确)`);
      } else {
        console.log(`  ❌ 大小期数${current.id}: 状态转换异常 (${current.status} -> ${next.status})`);
        diceOrderValid = false;
      }
    }

    // 检查赤壁玩法执行顺序
    let chibiOrderValid = true;
    for (let i = 0; i < chibiHistory.length - 1; i++) {
      const current = chibiHistory[i];
      const next = chibiHistory[i + 1];
      
      // 检查是否有正确的状态转换：下注中 -> 开奖中 -> 已结算
      if (current.status === 1 && next.status === 2) {
        console.log(`  ✅ 赤壁期数${current.id}: 下注中 -> 开奖中 (正确)`);
      } else if (current.status === 2 && next.status === 3) {
        console.log(`  ✅ 赤壁期数${current.id}: 开奖中 -> 已结算 (正确)`);
      } else {
        console.log(`  ❌ 赤壁期数${current.id}: 状态转换异常 (${current.status} -> ${next.status})`);
        chibiOrderValid = false;
      }
    }

    // 总结
    console.log('\n📋 定时任务优化验证结果:');
    console.log(`  🎲 大小玩法执行顺序: ${diceOrderValid ? '✅ 正确' : '❌ 异常'}`);
    console.log(`  ⚔️ 赤壁玩法执行顺序: ${chibiOrderValid ? '✅ 正确' : '❌ 异常'}`);
    
    if (diceOrderValid && chibiOrderValid) {
      console.log('  🎉 定时任务优化成功！执行顺序完全正确！');
    } else {
      console.log('  ⚠️ 定时任务执行顺序存在问题，需要进一步检查！');
    }
  }

  async cleanup() {
    if (this.connection) {
      await this.connection.end();
      console.log('✅ 数据库连接已关闭');
    }
    if (this.ws) {
      this.ws.close();
      console.log('✅ WebSocket连接已关闭');
    }
  }
}

// 运行测试
async function runTest() {
  const tester = new CasinoSchedulerTester();
  
  try {
    await tester.connect();
    
    // 等待测试完成
    setTimeout(async () => {
      await tester.cleanup();
      process.exit(0);
    }, 120000); // 2分钟后结束测试
    
  } catch (error) {
    console.error('❌ 测试失败:', error);
    await tester.cleanup();
    process.exit(1);
  }
}

// 处理程序退出
process.on('SIGINT', async () => {
  console.log('\n🛑 测试被中断');
  process.exit(0);
});

runTest();
